import LazyLoad from "@/components/LazyLoad";
import PrivateRoute from "@/components/PrivateRoute";
import { MenuModel } from "@/core/models/system.model";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { getMenuList } from "@/store/thunks/appThunk";
import LoginPage from "@/views/login";
import { Skeleton } from "@arco-design/web-react";
import React, { Suspense, useEffect } from "react";
import { Routes, Route, Navigate } from "react-router-dom";
const Layout = React.lazy(() => import("@/views/layout/index.tsx"));

export default function Router() {
  const dispatch = useAppDispatch();
  const menuList = useAppSelector((state) => state.app.menuList);
  useEffect(() => {
    dispatch(getMenuList());
  }, []);

  const getParentElement = (menu: MenuModel) => {
    if (menu.children && menu.children.length) {
      return null;
    } else {
      return (
        <PrivateRoute
          loader={() => {
            return {
              title: menu.name,
              icon: menu.icon,
              fixed: menu.fixed,
            };
          }}
        >
          {LazyLoad("/" + menu.path)}
        </PrivateRoute>
      );
    }
  };

  const getPath = (menu: MenuModel) => {
    if (menu.children && menu.children.length) {
      return `${menu.path}/*`;
    } else {
      return menu.path;
    }
  };

  return (
    <Routes>
      <Route path="/" element={<Navigate to="/index" />}></Route>
      <Route path="/login" element={<LoginPage />}></Route>
      <Route path="/*" element={<Layout />}>
        {menuList.map((menu) => (
          <Route
            key={getPath(menu)}
            element={getParentElement(menu)}
            path={menu.path}
          >
            {menu.children &&
              menu.children.map((child) => (
                <Route
                  key={child.path}
                  element={
                    <Suspense fallback={<Skeleton />}>
                      <PrivateRoute
                        loader={() => {
                          return {
                            title: child.name,
                            icon: child.icon,
                            fixed: child.fixed,
                          };
                        }}
                      >
                        {LazyLoad("/" + menu.path + "/" + child.path)}
                      </PrivateRoute>
                    </Suspense>
                  }
                  path={child.path}
                ></Route>
              ))}
          </Route>
        ))}
      </Route>
    </Routes>
  );
}
